package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
	"log"
	"net/http"
	"uyoung.co/ginEssential/common"
	"uyoung.co/ginEssential/dto"
	"uyoung.co/ginEssential/model"
	"uyoung.co/ginEssential/response"
	"uyoung.co/ginEssential/util"
)

func Register(c *gin.Context)  {
	DB := common.GetDB()
	// 获取参数
	name := c.PostForm("name")
	telephone := c.PostForm("telephone")
	passwrod := c.PostForm("passwrod")
	// 数据验证
	if len(telephone) != 11 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "手机必须为11位")
		return
	}
	if len(passwrod) < 6 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位")
		return
	}
	if len(name) == 0 {
		name = util.RandomString(10)
	}
	
	//log.Printf(name, telephone, passwrod)
	// 判断手机号是否存在
	if isTelephoneExist(DB, telephone) {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户已经存在")
		return
	}
	// 创建用户
	hasedPassword, err := bcrypt.GenerateFromPassword([]byte(passwrod), bcrypt.DefaultCost)
	if err != nil {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "加密错误")
		return
	}
	newUser := model.User{
		Name: name,
		Telephone: telephone,
		Password: string(hasedPassword),
	}
	DB.Create(&newUser)
	
	// 返回结果
	response.Success(c, nil, "注册成功")
}

func Login(c *gin.Context)  {
	DB := common.GetDB()
	// 获取参数
	telephone := c.PostForm("telephone")
	passwrod := c.PostForm("passwrod")
	// 数据验证
	if len(telephone) != 11 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "手机必须为11位")
		return
	}
	if len(passwrod) < 6 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位")
		return
	}
	// 判断手机号是否存在
	var user model.User
	DB.Where("telephone = ?", telephone).First(&user)
	if user.ID == 0 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户不存在")
		return
	}
	// 判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(passwrod)); err != nil {
		response.Response(c, http.StatusBadRequest, 400, nil, "密码错误")
		return
	}
	// 发放token
	token, err := common.ReleaseToken(user)
	if err != nil {
		response.Response(c, http.StatusInternalServerError, 500, nil, "系统异常")
		log.Printf("token genrate error：%v", err)
		return
	}
	// 返回结果
	response.Success(c, gin.H{"token": token}, "登陆成功")
}

func Info(c *gin.Context)  {
	user, _ := c.Get("user")
	
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg": "获取信息成功",
		"data": gin.H{"user": dto.ToUserDto(user.(model.User))},
	})
}




func isTelephoneExist(db *gorm.DB, telephone string) bool {
	var user model.User
	if err := db.Where("telephone = ?", telephone).First(&user).Error; err != nil {
		log.Println(err)
	}
	if user.ID != 0 {
		return true
	}
	
	return false
}